#include "groupchat.h"
#include "ui_groupchat.h"
#include "tcpclient.h"
#include <QMessageBox>
#include <QDateTime>
#include"tipwidget.h"

//静态成员变量类外初始化
groupChat* groupChat::m_instance = nullptr;
QMutex groupChat::m_mutex;

groupChat::groupChat(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::groupChat)
{
    ui->setupUi(this);

    // //获取当前文本光标对象
    // m_cursor = ui->showMsgTextEdit->textCursor();
    // //将光标移动到末尾
    // m_cursor.movePosition(QTextCursor::End);


    setWindowIcon(QIcon(":/img/mesBroadcasting.png"));
    setWindowTitle("消息广播-"+TcpClient::getInstance().usrName());
    setFixedSize(700,500);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 滚动区域
    scrollArea = new QScrollArea;
    scrollArea->setWidgetResizable(true);

    QWidget *chatContent = new QWidget;
    chatContent->setObjectName("chatContent");
    chatContent->setStyleSheet("#chatContent{border-image: url(:/img/background2.png);}");
    chatLayout = new QVBoxLayout(chatContent);
    chatLayout->setAlignment(Qt::AlignTop); // 消息从上往下堆叠
    scrollArea->setWidget(chatContent);

    mainLayout->addWidget(scrollArea);

    // 底部输入框
    QHBoxLayout *inputLayout = new QHBoxLayout;
    input = new QLineEdit;
    QPushButton *sendBtn = new QPushButton("发送");
    inputLayout->addWidget(input);
    inputLayout->addWidget(sendBtn);
    input->setFixedHeight(40);
    sendBtn->setFixedSize(100,40);
    input->setStyleSheet("QLineEdit {"
                         "font-size:18px;"
                         "font-family: 'SimSun';"
                         "border: 2px solid rgb(180, 172, 169);"
                         "border-radius: 5px;"
                         "}"
                         );
    sendBtn->setStyleSheet(
        "QPushButton {"
        "font-family: 'SimSun';"
        "font-weight:bold;"
        "background-color:	rgb(244, 239, 255);"
        "border: 2px solid rgb(180, 172, 169); "
        "border-radius: 5px;}"

        "QPushButton:pressed{"
        "background-color:rgb(226, 221, 236);}"
        );

    sendBtn->setShortcut(Qt::Key_Return);
    mainLayout->addLayout(inputLayout);
    connect(sendBtn, &QPushButton::clicked, this, &groupChat::sendMessage);
}

groupChat::~groupChat()
{
    delete ui;
}

//静态成员函数
groupChat *groupChat::getInstance()
{
    QMutexLocker locker(&m_mutex);
    if(!m_instance){
        m_instance=new groupChat;
    }
    return m_instance;
}

void groupChat::release()
{
    QMutexLocker locker(&m_mutex);
    if(m_instance)
    {
        delete m_instance;
        m_instance=nullptr;
    }
}

//发送消息
void groupChat::sendMessage()
{
    QString msg=input->text();
    msg=msg.trimmed();
    if(!msg.isEmpty()){
        QString usrName=TcpClient::getInstance().usrName();
        QDateTime current = QDateTime::currentDateTime();
        QString strTime = current.toString("yyyy-MM-dd HH:mm:ss");
        QString strMsg = QString("["+usrName+"]"+strTime);

        // appendLine(strMsg+"\n"+msg,Qt::blue,Qt::AlignRight,QColor(250, 239, 255));
        appendLine(msg,strMsg,0);
        input->clear();
        TcpClient::getInstance().groupChat(msg);
    }else{
        TipWidget::getInstance()->showTip("信息不能为空", TipWidget::Warning, 1000, this);
    }
}

//接收消息
void groupChat::updateGroupShowMsg(QString msg, QString timeText)
{
    appendLine(msg,timeText,1);
    // appendLine(jointMsg,Qt::black,Qt::AlignLeft,QColor(251, 255, 244));
}

//设置消息格式并填充
void groupChat::appendLine(const QString &text,
                           const QColor &color,
                           Qt::Alignment alignment,
                           const QColor& bgColor) {

    // // 创建段落格式
    // QTextBlockFormat blockFormat;
    // blockFormat.setAlignment(alignment);
    // blockFormat.setBackground(QBrush(bgColor));

    // // 创建字符格式
    // QTextCharFormat charFormat;
    // charFormat.setForeground(color);

    // // 应用格式并插入文本
    // m_cursor.insertBlock(blockFormat, charFormat);
    // m_cursor.insertText(text);

    // // 确保后续内容从新行开始
    // m_cursor.insertBlock();

    // //获取当前文本光标对象
    // m_cursor = ui->showMsgTextEdit->textCursor();
    // //将光标移动到末尾
    // m_cursor.movePosition(QTextCursor::End);
    // // 确保光标可见（自动滚动）
    // ui->showMsgTextEdit->ensureCursorVisible();
}

void groupChat::appendLine(const QString &text, const QString &timeText, int bubbleType)
{
    if(bubbleType==0){
        chatLayout->addWidget(new ChatBubble(timeText,ChatBubble::Myself,true));
        chatLayout->addWidget(new ChatBubble(text,ChatBubble::Myself,false));
    }else{
        chatLayout->addWidget(new ChatBubble(timeText,ChatBubble::Other,true));
        chatLayout->addWidget(new ChatBubble(text,ChatBubble::Other,false));
    }
}
